package com.nolon.flange.viewmodel

import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Environment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.nolon.flange.R
import com.nolon.flange.dao.ProjectDao
import com.nolon.flange.extensions.toast
import com.nolon.flange.model.FileItem
import com.nolon.flange.model.Project
import com.nolon.flange.repository.ProjectRepository
import com.nolon.flange.tools.FileTools
import kotlinx.coroutines.launch
import n.Mediator

class ProjectViewModel(private val projectDao: ProjectDao, application: Application) :
    AndroidViewModel(application) {
    private val repository: ProjectRepository = ProjectRepository(application)

    val projects: LiveData<List<Project>> = projectDao.getAll()
    val files: MutableLiveData<List<FileItem>> = MutableLiveData(arrayListOf())

    suspend fun insertProject(project: Project) {
        viewModelScope.launch {
            projectDao.insert(project)
        }
    }

    suspend fun insertProject2(project: Project): Long = projectDao.insert(project)

    fun removeProject(project: Project) {
        viewModelScope.launch {
            repository.deleteProject(project)
        }
    }

    fun renameProject(context: Context, project: Project, text: String?) {
        if (text.isNullOrEmpty()) {
            toast(context, context.getString(R.string.require_new_name))
            return
        }
        viewModelScope.launch {
            repository.updateProject(
                project.copy(
                    name = text,
                    modified = System.currentTimeMillis()
                )
            )
        }
    }

    fun refreshFiles(context: Context) {
        viewModelScope.launch {
            if (Build.VERSION.SDK_INT < 29) {
                val dir =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                val fs = dir.listFiles()?.map {
                    FileItem(it)
                }?.filter { it.name.endsWith("xls") }
                if (!fs.isNullOrEmpty()) {
                    files.value = fs
                }
            } else {
                val fs = FileTools.getAllXls(context)
                files.value = fs
            }
        }
    }

    /**
     * 生成信息存到SharePreference
     */
    fun genInfo(c: Context) {
        viewModelScope.launch {
            try {
                Mediator.init(c)
            }catch (e:Exception){

            }
        }
    }

    val activationMessage: MutableLiveData<String> = MutableLiveData()

}